package com.sdgakj.rest;

import com.sdgakj.entity.Person;
import com.sdgakj.entity.User;
import com.sdgakj.service.login.LoginByWechatService;
import com.sdgakj.service.person.PersonService;
import com.sdgakj.utils.SignUtil;
import org.apache.shiro.web.session.HttpServletSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by win10 on 2017/5/24.
 */
/*@RestController()*/
@Controller
@RequestMapping("/api/v1/common")
public class CommonRestController {
    private static Logger logger = LoggerFactory.getLogger(CommonRestController.class);

    @Autowired
    private LoginByWechatService loginByWechatService;

    @Autowired
    private PersonService personService;
    /**
     * 确认消息来自微信服务器
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/check")
    String check(HttpServletRequest request) {

        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

     //   String code=request.getParameter("code");
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        }else{
            return "fail";
        }
    }
    /*
    * 微信登录
    * */
    @RequestMapping(value = "/weixinLogin")
    public String weixinLogin(Model model,String code){
        String reuqest="";
       if(code!=null) {
           logger.info("用户已同意微信授权请求");
           User user = loginByWechatService.weixinLogin(code);
           if(user!=null){
                model.addAttribute("userId",user.getId());
                model.addAttribute("name",user.getName());
                model.addAttribute("loginName",user.getLoginName());
               if(user.getMobile()!=null) {
                   model.addAttribute("mobile", user.getMobile());
               }
                Person person=personService.getPersonByUserId(user.getId());
                if(person!=null){
                    model.addAttribute("personId",person.getId());
                }
               model.addAttribute("mess","0");
            /*   System.out.println("用户信息："+user.getId());*/
               reuqest="h5/index/index";
           }
       }
        return  reuqest;
    }
}

